package cn.sfa.controller.meeting;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DateUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.meeting.SaleMeeting;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.meeting.MeetingService;

/**
 * 
* 类名称：MeetingController   
* 类描述： 早会管理处理类
* 创建人：LLY   
* 创建时间：2012-2-27  
* 修改人：LLY   
* 修改时间：2012-2-27   
* 修改备注：   
* @version
 */
@Controller
@RequestMapping("routine/meeting/index")
public class MeetingController extends WebInitBinderContoller{

	Logger log = LoggerFactory.getLogger(MeetingController.class);
	@Autowired
	LoginService loginService;
	@Autowired
	MeetingService meetingService;
	@Autowired
	AffixService affixService;
	private Pagination pagination;//分页
	
	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}
	
	/**
	 * 转到添加早会页面
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping("/addmeeting")
	public String addMeeting(SaleMeeting saleMeeting,HttpServletRequest request)
	{
		return "/meeting/addmeeting";
	}
	
	
	@RequestMapping("/validate")
	public void validate(SaleMeeting saleMeeting,HttpServletRequest request,ModelMap map,
			HttpServletResponse response) throws Exception
	{
		int count=0;
		String json="";
		String meetingTitle="";
		String meetingContent="";
		//表单验证
		if(CommonUtil.isEmpty(saleMeeting.getMeetingTitle()))
		{
			meetingTitle="早会标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleMeeting.getMeetingContent()))
		{
			meetingContent="早会内容不能为空！";
			count=count+1;
		}else if(saleMeeting.getMeetingTitle().length()<6 || saleMeeting.getMeetingTitle().length()>50)
		{
			meetingTitle="早会标题长度必须在6到50位";
			count=count+1;

		}else if(saleMeeting.getMeetingContent().length()>100000)
		{
			meetingContent= "早会内容长度必须小于100000位";
			count=count+1;
		}
		
		PrintWriter out=response.getWriter();
		boolean result=count==0;
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("meetingTitle", meetingTitle);
            temp.put("meetingContent",meetingContent);
            
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	/**
	 * 添加早会
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping("/add")
	public void add(SaleMeeting saleMeeting,HttpServletRequest request,ModelMap map,
			HttpServletResponse response,
			@RequestParam(value="affixStr",required=false)String affixStr,
			@RequestParam(value = "mCount", required = false) String mcount,
			@RequestParam(value="sDate",required=false) String sDate,
			@RequestParam(value="eDate",required=false) String eDate) throws Exception
	{
		
		PrintWriter out=response.getWriter();
		
		
		String isAffix=request.getParameter("isAffix");

		
		int count=0;
		String json="";
		String meetingTitle="";
		String meetingContent="";
		String affixPat="";
		String add="";
		String startDate="";
		String endDate="";
		String meetingCount="";
		if(CommonUtil.isEmpty(saleMeeting.getMeetingTitle()))
		{
			meetingTitle="早会标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleMeeting.getMeetingContent()))
		{
			meetingContent="早会内容不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(mcount))
		{
			meetingCount="早会人数不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(sDate))
		{
			startDate="早会开始时间不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(eDate))
		{
			endDate="早会结束时间不能为空！";
			count=count+1;
		}
		else if(saleMeeting.getMeetingTitle().length()<6 || saleMeeting.getMeetingTitle().length()>50)
		{
			meetingTitle="早会标题长度必须在6到50位";
			count=count+1;
		}else if(saleMeeting.getMeetingContent().length()>100000)
		{
			meetingContent="早会内容长度必须小于100000位";
			count=count+1;
		}else if(!FormValidate.isNumber(mcount))
		{
			meetingCount="早会人数必须为数字";
			count=count+1;
		} else if(DateUtil.stringToDate2(eDate).getTime()-DateUtil.stringToDate2(sDate).getTime()<0)
		{
			endDate="早会结束时间必须大于早会开始时间！";
			count=count+1;
		}
		boolean result=count==0;
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		if(result)
		{
			saleMeeting.setCreateUid(user.getSaleUsersLoginId());
			saleMeeting.setCreateDate(new Date());
			saleMeeting.setUpdateDate(new Date());
			saleMeeting.setStartDate(DateUtil.stringToDate2(sDate));
			saleMeeting.setEndDate(DateUtil.stringToDate2(eDate));
			saleMeeting.setUpdateId(user.getSaleUsersLoginId());
			saleMeeting.setMeetingMaster(user.getSaleUsersLoginId());
			saleMeeting.setMeetingStatus("APPLYSTATUS_1");//未申请状态
			saleMeeting.setMeetingCount(Integer.parseInt(mcount));
			boolean flag=meetingService.addMeeting(saleMeeting,"N");
			if(flag)
			{
				try {
					//保存附件
					affixService.saveAffix(affixStr, "SALEMEETING", saleMeeting.getSaleMeetingId());
					add="添加早会成功！";
				} catch (Exception e) {
					add="添加早会失败！";
				}
				
				map.put("meeting", saleMeeting);
			}else 
			{
				add="添加早会失败！";
			}
			}
		
		
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

        
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("add", add);
            temp.put("meetingTitle",meetingTitle);
            temp.put("meetingContent",meetingContent);
            temp.put("startDate",startDate);
            temp.put("endDate",endDate);
            temp.put("meetingCount", meetingCount);
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	
	
	/**
	 * 管理早会页面
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping(value="/getmeetings")
	public String manageNews(@RequestParam(value="currentPage", required=false) String currentPage
			,SaleMeeting saleMeeting,HttpServletRequest request,ModelMap map,
			@RequestParam(value="beginCreateDate", required=false)String beginCreateDate,
			@RequestParam(value="endCreateDate", required=false)String endCreateDate)
	{	
		int pageIndex;
		try{
			pageIndex = Integer.valueOf(currentPage);
		}catch(Exception ex){
			pageIndex = 1;
		} 
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		Pagination pagination=null;
		pagination = meetingService.searchMeetings(
				pageIndex,10,request.getContextPath()+"/routine/meeting/index/getmeetings?" +
						"meetingTitle="+CommonUtil.jugeAndFixNull(saleMeeting.getMeetingTitle())+
						"&meetingContent="+CommonUtil.jugeAndFixNull(saleMeeting.getMeetingContent())+
						"&masterName="+CommonUtil.jugeAndFixNull(saleMeeting.getMasterName())+
						"&meetingStatus="+CommonUtil.jugeAndFixNull(saleMeeting.getMeetingStatus())+
						"&beginCreateDate="+(CommonUtil.isEmpty(beginCreateDate)?"":beginCreateDate)+
						"&endCreateDate="+(CommonUtil.isEmpty(endCreateDate)?"":endCreateDate)
						,saleMeeting,user.getSaleUsersLoginId(),DateUtil.stringToDate2(beginCreateDate),DateUtil.stringToDate2(endCreateDate)); 
		 
		map.put("pagination", pagination);
		map.put("meetingTitle",saleMeeting.getMeetingTitle());
		map.put("meetingContent",saleMeeting.getMeetingContent());
		map.put("masterName",saleMeeting.getMasterName());
		map.put("meetingStatus",saleMeeting.getMeetingStatus());
		map.put("beginCreateDate",CommonUtil.isEmpty(beginCreateDate)?"": beginCreateDate);
		map.put("endCreateDate",CommonUtil.isEmpty(endCreateDate)?"": endCreateDate);
		map.put("page",pageIndex); 
 
		return "/meeting/getmeetings";
	}
	@RequestMapping("/delete/{saleMeetingId}")
	public void delete(HttpServletRequest request,HttpServletResponse response,@PathVariable("saleMeetingId")String saleMeetingId) throws IOException
	{
		response.setContentType("text/json");
		PrintWriter out=response.getWriter();
		SaleMeeting meeting=meetingService.getMeeting(saleMeetingId);
		if(!"APPLYSTATUS_2".equals(meeting.getMeetingStatus()))//只有正在审核状态不让删除
		{
			boolean flag=meetingService.deleteMeetingById(saleMeetingId);
			JSONObject jo = new JSONObject();
			jo.put("isDel", flag);
			out.print(jo);
			out.flush();
			out.close();
		}
	}
	
	/**
	 * 转到编辑页面
	 * @param request
	 * @param saleMeetingId
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value=("/updatemeeting/{saleMeetingId}"))
	public String updatenews(HttpServletRequest request,
			@PathVariable("saleMeetingId")String saleMeetingId,
			ModelMap map) throws IOException
	{
		SaleMeeting meeting=meetingService.getMeeting(saleMeetingId);
		request.setAttribute("meeting",meeting);
		if("APPLYSTATUS_1".equals(meeting.getMeetingStatus()) || "APPLYSTATUS_4".equals(meeting.getMeetingStatus()))
				{
		//附件列表
		List<SaleAffixItem> affixList = affixService.getAffix(
				"SALEMEETING", saleMeetingId);
		map.put("affixList", affixList);
		request.setAttribute("saleMeetingId", saleMeetingId);
		return "/meeting/updatemeeting";
				}
		return "redirect:/routine/meeting/index/getmeetings";
	}
	
	/**
	 * 编辑早会
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/edit"))
	public void update(SaleMeeting saleMeeting,HttpServletRequest request,ModelMap map,
			@RequestParam(value = "affixStr", required = false) String affixStr, // 附件列表
			@RequestParam(value = "mCount", required = false) String mcount,
			HttpServletResponse response,
			@RequestParam(value="sDate",required=false) String sDate,
			@RequestParam(value="eDate",required=false) String eDate) throws Exception
	{
		String saleMeetingId=request.getParameter("saleMeetingId");
		
		int count=0;
		String json="";
		String meetingTitle="";
		String meetingContent="";
		String affixPat="";
		String add="";
		String startDate="";
		String endDate="";
		String meetingCount="";
		SaleMeeting meeting=meetingService.getMeeting(saleMeetingId);
		if(CommonUtil.isEmpty(saleMeeting.getMeetingTitle()))
		{
			meetingTitle="早会标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleMeeting.getMeetingContent()))
		{
			meetingContent="早会内容不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(mcount))
		{
			meetingCount="早会人数不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(sDate))
		{
			startDate="早会开始时间不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(eDate))
		{
			endDate="早会结束时间不能为空！";
			count=count+1;
		}
		else if(saleMeeting.getMeetingTitle().length()<6 || saleMeeting.getMeetingTitle().length()>50)
		{
			meetingTitle="早会标题长度必须在6到50位";
			count=count+1;
		}else if(saleMeeting.getMeetingContent().length()>100000)
		{
			meetingContent="早会内容长度必须小于100000位";
			count=count+1;
		}else if(!FormValidate.isNumber(mcount))
		{
			meetingCount="早会人数必须为数字";
			count=count+1;
		} else if(DateUtil.stringToDate2(eDate).getTime()-DateUtil.stringToDate2(sDate).getTime()<0)
		{
			endDate="早会结束时间必须大于早会开始时间！";
			count=count+1;
		}
		boolean result=count==0;
		
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");

		
		
		if(result)
		{
			saleMeeting.setSaleMeetingId(saleMeetingId);
			saleMeeting.setUpdateDate(new Date());
			saleMeeting.setStartDate(DateUtil.stringToDate2(sDate));
			saleMeeting.setEndDate(DateUtil.stringToDate2(eDate));
			saleMeeting.setUpdateId(user.getSaleUsersLoginId());
			saleMeeting.setMeetingCount(Integer.parseInt(mcount));
			boolean flag=meetingService.updateMeeting(saleMeeting);
			if(flag)
			{
				try {
					//保存附件
					affixService.saveAffix(affixStr, "SALEMEETING", saleMeetingId);
					add="编辑早会成功！";
				} catch (Exception e) {
					add="编辑早会失败！";
				}
			}else 
			{
				add="编辑早会失败！";
			}
			
		}
		

		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

        
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("add", add);
            temp.put("meetingTitle",meetingTitle);
            temp.put("meetingContent",meetingContent);
            temp.put("startDate",startDate);
            temp.put("endDate",endDate);
            temp.put("meetingCount", meetingCount);
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	
	/**
	 * 查看早会
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/view"))
	public String view(HttpServletRequest request,ModelMap map,
			HttpServletResponse response) throws Exception
	{
		String saleMeetingId=request.getParameter("saleMeetingId");
		SaleMeeting saleMeeting=meetingService.getMeeting(saleMeetingId);
		map.put("meeting", saleMeeting);
		//附件列表
		List<SaleAffixItem> affixList = affixService.getAffix(
				"SALEMEETING", saleMeetingId);
		map.put("affixList", affixList);
		return "/meeting/view";
	}
	
	
	/**
	 * 申请审核
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/apply"))
	public void apply(HttpServletRequest request,ModelMap map,
			@RequestParam(value="saleMeetingId",required=false)String saleMeetingId,
			@RequestParam(value="status",required=false)String status,
			HttpServletResponse response) throws Exception
	{
			SaleMeeting saleMeeting=meetingService.getMeeting(saleMeetingId);
			saleMeeting.setMeetingStatus(status);
			boolean flag=meetingService.updateMeetingStatus(saleMeeting);
			response.setContentType("text/json");
			PrintWriter out=response.getWriter();
			SaleMeeting meeting=meetingService.getMeeting(saleMeetingId);
			JSONObject jo = new JSONObject();
			jo.put("isDel", flag);
			out.print(jo);
			out.flush();
			out.close();
			
	}
}
